{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false,
    "id": "Lug-i9Ang0Cn"
   },
   "source": [
    "# Получение рекомендаций в Spotify с помощью GigaChat\n",
    "\n",
    "Этот ноутбук показывает, как можно получать рекомендаций в Spotify c помощью GigaChat.\n",
    "Получить Client Id и Client Secret в Spotify можно [тут](https://developer.spotify.com/dashboard)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "AOL5NCErg0Cp",
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "!pip install spotipy gigachain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true,
    "id": "W02mN_okg0Cq",
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import sys\n",
    "\n",
    "import spotipy\n",
    "from langchain.agents import AgentExecutor, ZeroShotAgent\n",
    "from langchain.chat_models import GigaChat\n",
    "from langchain.tools import Tool\n",
    "from spotipy.oauth2 import SpotifyClientCredentials"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "9SABf0t2g0Cq"
   },
   "outputs": [],
   "source": [
    "os.environ[\"SP_ID\"] = \"<Spotify Client ID>\"\n",
    "os.environ[\"SP_SECRET\"] = \"<Spotify Client Secret>\"\n",
    "\n",
    "llm = GigaChat()  # Use big model of GigaChat\n",
    "\n",
    "spotify = spotipy.Spotify(\n",
    "    client_credentials_manager=SpotifyClientCredentials(\n",
    "        client_id=os.getenv(\"SP_ID\"), client_secret=os.getenv(\"SP_SECRET\")\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "RA5Ksuukg0Cr",
    "outputId": "edb8e141-111b-4fa7-b960-5aa4d81c05bd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m-----\n",
      "Thought: Создать плейлист с настроением грусть и жанрами, которые подходят для такого настроения\n",
      "Action: CREATE_PLAYLIST\n",
      "Action Input: {\"happiness\": 0, \"genres\": [\"sad\", \"ballads\", \"love-songs\"]}\n",
      "\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mJohn Murphy — In the House - In a Heartbeat\n",
      "Lana Del Rey — Carmen\n",
      "Céline Dion — My Heart Will Go On (Love Theme from \"Titanic\")\n",
      "Lifehouse — Everything\n",
      "Touché Amoré — Condolences\n",
      "Of Mice & Men — My Understandings\n",
      "Coldplay — Warning Sign\n",
      "Sigur Rós — Untitled #1 (Vaka)\n",
      "Troye Sivan — Happy Little Pill\n",
      "B.o.B — Both of Us (feat. Taylor Swift)\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "John Murphy — In the House - In a Heartbeat\n",
      "Lana Del Rey — Carmen\n",
      "Céline Dion — My Heart Will Go On (Love Theme from \"Titanic\")\n",
      "Lifehouse — Everything\n",
      "Touché Amoré — Condolences\n",
      "Of Mice & Men — My Understandings\n",
      "Coldplay — Warning Sign\n",
      "Sigur Rós — Untitled #1 (Vaka)\n",
      "Troye Sivan — Happy Little Pill\n",
      "B.o.B — Both of Us (feat. Taylor Swift)\n"
     ]
    }
   ],
   "source": [
    "def create_playlist(data):\n",
    "    \"\"\"Функция получения рекомендаций\"\"\"\n",
    "    data = json.loads(data)\n",
    "    kwargs = {}\n",
    "    if \"energy\" in data:\n",
    "        kwargs[\"target_energy\"] = data[\"energy\"] / 100\n",
    "    if \"happiness\" in data:\n",
    "        kwargs[\"target_valence\"] = data[\"happiness\"] / 100\n",
    "    if \"dance\" in data:\n",
    "        kwargs[\"target_danceability\"] = data[\"dance\"] / 100\n",
    "    if \"genres\" in data:\n",
    "        kwargs[\"seed_genres\"] = data[\"genres\"][:5]\n",
    "    else:\n",
    "        kwargs[\"seed_genres\"] = [\"pop\", \"hip-hop\", \"rock\", \"r-n-b\"]\n",
    "\n",
    "    results = spotify.recommendations(limit=10, **kwargs)\n",
    "    tracks = []\n",
    "    for track in results[\"tracks\"]:\n",
    "        name = f\"{track['artists'][0]['name']} — {track['name']}\"\n",
    "        os.write(1, f\"{name}\\n\".encode())\n",
    "        tracks.append(name)\n",
    "\n",
    "    return \"\\n\".join(tracks)\n",
    "\n",
    "\n",
    "tools = [\n",
    "    Tool.from_function(\n",
    "        func=create_playlist,\n",
    "        return_direct=True,\n",
    "        name=\"CREATE_PLAYLIST\",\n",
    "        description=\"\"\"Описание: создает плейлисты \\n Параметры:\n",
    "        {{\"happiness\": число которое обозначает настроение запроса где 0 - грусть, печаль, агрессивность и 100 - счастье, веселье\n",
    "         \"energy\": число которое обозначает энергичность запроса где 0 — спокойствие и 100 — энергичность не обязательный параметр,\n",
    "         \"dance\": число которое обозначает танцевальность где 0 - спокойствие и 100 — танцевальная музыка не обязательный параметр,\n",
    "         \"genres\": список от 1 до 5 элементов выбранных из этого списка [\"acoustic\", \"afrobeat\", \"alt-rock\", \"alternative\", \"ambient\", \"anime\", \"black-metal\", \"bluegrass\", \"blues\", \"bossanova\", \"brazil\", \"breakbeat\", \"british\", \"cantopop\", \"chicago-house\", \"children\", \"chill\", \"classical\", \"club\", \"comedy\", \"country\", \"dance\", \"dancehall\", \"death-metal\", \"deep-house\", \"detroit-techno\", \"disco\", \"disney\", \"drum-and-bass\", \"dub\", \"dubstep\", \"edm\", \"electro\", \"electronic\", \"emo\", \"folk\", \"forro\", \"french\", \"funk\", \"garage\", \"german\", \"gospel\", \"goth\", \"grindcore\", \"groove\", \"grunge\", \"guitar\", \"happy\", \"hard-rock\", \"hardcore\", \"hardstyle\", \"heavy-metal\", \"hip-hop\", \"holidays\", \"honky-tonk\", \"house\", \"idm\", \"indian\", \"indie\", \"indie-pop\", \"industrial\", \"iranian\", \"j-dance\", \"j-idol\", \"j-pop\", \"j-rock\", \"jazz\", \"k-pop\", \"kids\", \"latin\", \"latino\", \"malay\", \"mandopop\", \"metal\", \"metal-misc\", \"metalcore\", \"minimal-techno\", \"movies\", \"mpb\", \"new-age\", \"new-release\", \"opera\", \"pagode\", \"party\", \"philippines-opm\", \"piano\", \"pop\", \"pop-film\", \"post-dubstep\", \"power-pop\", \"progressive-house\", \"psych-rock\", \"punk\", \"punk-rock\", \"r-n-b\", \"rainy-day\", \"reggae\", \"reggaeton\", \"road-trip\", \"rock\", \"rock-n-roll\", \"rockabilly\", \"romance\", \"sad\", \"salsa\", \"samba\", \"sertanejo\", \"show-tunes\", \"singer-songwriter\", \"ska\", \"sleep\", \"songwriter\", \"soul\", \"soundtracks\", \"spanish\", \"study\", \"summer\", \"swedish\", \"synth-pop\", \"tango\", \"techno\", \"trance\", \"trip-hop\", \"turkish\", \"work-out\", \"world-music\"]}}''\n",
    "         \"\"\",  # noqa: E501,\n",
    "    ),\n",
    "]\n",
    "\n",
    "agent = ZeroShotAgent.from_llm_and_tools(llm=llm, tools=tools)\n",
    "agent_executor = AgentExecutor.from_agent_and_tools(\n",
    "    agent=agent, tools=tools, verbose=True\n",
    ")\n",
    "\n",
    "stdout = sys.stdout\n",
    "\n",
    "sys.stdout = stdout\n",
    "\n",
    "print(\n",
    "    agent_executor.run(\n",
    "        \"Создай мне грустный плейлист, когда хочется сбежать от всех проблем\"\n",
    "    )\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "langchain",
   "language": "python",
   "name": "langchain"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
